package com.lixinlei.meetingfilm.showhystrix.command;

import com.netflix.hystrix.*;
import org.assertj.core.util.Lists;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * List<String> - 批量返回的结果
 * String - 批量里面，每一次处理的返回结果
 * Integer - 批量里面，每一次处理的请求内容
 */
public class CommandCollapser extends HystrixCollapser<List<String>, String, Integer> {

    private Integer id;

    public CommandCollapser(Integer id){
        super(Setter
                .withCollapserKey(HystrixCollapserKey.Factory.asKey("CommandCollapser"))
                .andCollapserPropertiesDefaults(
                        HystrixCollapserProperties.defaultSetter()
                                .withTimerDelayInMilliseconds(1000)
                )
        );
        this.id = id;
    }

    /**
     * @Description: 获取请求参数
     * @Param: []
     * @return: java.lang.Integer
     * @Author: jiangzh
     */
    @Override
    public Integer getRequestArgument() {
        return id;
    }

    /**
     * 批量业务处理
     * @param collection 批量的请求
     * @return 执行批量请求的 Command；
     */
    @Override
    protected HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, Integer>> collection) {
        return new BatchCommand(collection);
    }

    /**
     * 批量处理结果与请求业务之间映射关系处理
     * @param strings 批量的执行结果
     * @param collection 批量的响应
     */
    @Override
    protected void mapResponseToRequests(List<String> strings, Collection<CollapsedRequest<String, Integer>> collection) {
        int counts = 0;
        Iterator<HystrixCollapser.CollapsedRequest<String, Integer>> iterator = collection.iterator();
        while (iterator.hasNext()) {
            HystrixCollapser.CollapsedRequest<String, Integer> response = iterator.next();
            String result = strings.get(counts ++);
            response.setResponse(result);
        }
    }

}

class BatchCommand extends HystrixCommand<List<String>> {

    private Collection<HystrixCollapser.CollapsedRequest<String, Integer>> collection;

    public BatchCommand(Collection<HystrixCollapser.CollapsedRequest<String, Integer>> collection){
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("BatchCommand")));
        this.collection = collection;
    }

    /**
     * 从批量请求中拿到参数，执行，返回批量结果；
     * @return List<String> 批量请求的结果
     * @throws Exception
     */
    @Override
    protected List<String> run() throws Exception {
        System.err.println("currentThread : " + Thread.currentThread().getName());
        List<String> result = Lists.newArrayList();

        Iterator<HystrixCollapser.CollapsedRequest<String, Integer>> iterator = collection.iterator();
        while (iterator.hasNext()) {
            HystrixCollapser.CollapsedRequest<String, Integer> request = iterator.next();
            Integer reqParam = request.getArgument();
            // 具体业务逻辑
            result.add("Mooc req: " + reqParam);
        }

        return result;
    }

}
